'use client'

import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Heart, Calendar } from 'lucide-react'
import { PieChart, Pie, Cell, ResponsiveContainer } from 'recharts'
import { createClient } from '@/lib/supabase/client'
import { cn } from '@/lib/utils'

// 定义情绪类型
type Mood = 'happy' | 'sad' | 'anxious' | 'angry' | 'calm' | 'excited'

// 情绪颜色映射
const moodColors = {
  happy: '#86EFAC',
  sad: '#93C5FD',
  anxious: '#FCA5A5',
  angry: '#FB923C',
  calm: '#A5B4FC',
  excited: '#FCD34D'
}

// 情绪标签映射
const moodLabels = {
  happy: 'Happy',
  sad: 'Sad',
  anxious: 'Anxious',
  angry: 'Angry',
  calm: 'Calm',
  excited: 'Excited'
}

// 模拟数据 - 实际应用中应从数据库获取
const mockMoodData = [
  { name: 'Happy', value: 40 },
  { name: 'Sad', value: 15 },
  { name: 'Anxious', value: 10 },
  { name: 'Angry', value: 5 },
  { name: 'Calm', value: 20 },
  { name: 'Excited', value: 10 }
]

export default function MoodPage() {
  const [selectedMood, setSelectedMood] = useState<Mood | null>(null)
  const [moodNote, setMoodNote] = useState('')
  const [submitted, setSubmitted] = useState(false)
  const supabase = createClient()

  const handleMoodSelect = (mood: Mood) => {
    setSelectedMood(mood === selectedMood ? null : mood)
  }

  const handleSubmit = async () => {
    if (!selectedMood) return

    try {
      // 在实际应用中，这里应该将情绪数据保存到数据库
      // 此处仅为演示
      await new Promise(resolve => setTimeout(resolve, 500))
      setSubmitted(true)
      setTimeout(() => setSubmitted(false), 2000)
      setSelectedMood(null)
      setMoodNote('')
    } catch (error) {
      console.error('Error submitting mood:', error)
    }
  }

  return (
    <div className="min-h-screen" style={{ backgroundColor: '#FAF9F5' }}>
      <div className="max-w-4xl mx-auto p-8">
        <Card className="mb-8">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Heart className="text-facet-wine-primary" />
              Mood Tracking
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="mb-6 text-gray-600">How are you feeling today? Select your current mood:</p>

            {/* 情绪选择器 */}
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-4 mb-6">
              {Object.keys(moodLabels).map((moodKey) => {
                const mood = moodKey as Mood
                return (
                  <div
                    key={mood}
                    onClick={() => handleMoodSelect(mood)}
                    className={cn(
                      'p-4 rounded-xl cursor-pointer transition-all duration-300 flex flex-col items-center justify-center',
                      selectedMood === mood
                        ? 'ring-2 ring-facet-blue-primary transform scale-105'
                        : 'hover:bg-gray-100'
                    )}
                    style={{ backgroundColor: `${moodColors[mood]}20` }}
                  >
                    <div
                      className="w-12 h-12 rounded-full flex items-center justify-center mb-2"
                      style={{ backgroundColor: moodColors[mood] }}
                    >
                      <Heart className="h-6 w-6 text-white" />
                    </div>
                    <span className="text-sm font-medium">{moodLabels[mood]}</span>
                  </div>
                )
              })}
            </div>

            {/* 情绪笔记 */}
            {selectedMood && (
              <div className="mb-6">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Notes about your mood (optional)
                </label>
                <textarea
                  value={moodNote}
                  onChange={(e) => setMoodNote(e.target.value)}
                  className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-facet-blue-primary focus:border-transparent"
                  rows={3}
                  placeholder="What's contributing to your current mood?"
                />
              </div>
            )}

            {/* 提交按钮 */}
            <Button
              onClick={handleSubmit}
              disabled={!selectedMood}
              variant="facet"
              className="w-full"
            >
              {submitted ? 'Submitted!' : 'Log Your Mood'}
            </Button>
          </CardContent>
        </Card>

        {/* 情绪统计 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Calendar className="text-facet-blue-primary" />
              Mood Patterns
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-64">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={mockMoodData}
                    cx="50%"
                    cy="50%"
                    innerRadius={60}
                    outerRadius={80}
                    paddingAngle={5}
                    dataKey="value"
                    label={({ name, percent }) => `${name} ${(percent ? percent * 100 : 0).toFixed(0)}%`}
                  >
                    {mockMoodData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={moodColors[entry.name.toLowerCase() as Mood]} />
                    ))}
                  </Pie>
                </PieChart>
              </ResponsiveContainer>
            </div>
            <p className="text-center text-sm text-gray-500 mt-4">
              This is a visualization of your recent mood patterns.
            </p>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}